package com.alibaba.system.service.impl;


import com.alibaba.basic.service.impl.BaseServiceImpl;
import com.alibaba.system.domain.Menu;
import com.alibaba.system.mapper.MenuMapper;
import com.alibaba.system.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author itsource
 * @since 2023-03-09
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {

    @Autowired
    private MenuMapper mapper;

    @Override
    public List<Menu> first() {

        List<Menu> collect = mapper.findAll().stream().filter(menu -> Objects.nonNull(menu) && null == menu.getParentId()).collect(Collectors.toList());
        return collect;
    }

    /**
     * 无限集树
     * @return
     */
    @Override
    public List<Menu> tree() {
        List<Menu> result = new ArrayList<>();
        // 查询所有
        List<Menu> allMenus = mapper.findAll();
        // 将查询出来的数据转换成map
        Map<Long, Menu> menuMap = allMenus.stream().collect(Collectors.toMap(Menu::getId, menu -> menu));
        //  遍历 儿子找爹
        allMenus.stream().forEach(menu -> {
            if (null == menu.getParentId()){
                result.add(menu);
            } else {
                Menu paret = menuMap.get(menu.getParentId());
                paret.getChildren().add(menu);
            }

        });
        return result;
    }
}
